package com.qc.blogsystemplus.service;

import com.qc.blogsystemplus.bean.UserBean;
import com.qc.blogsystemplus.entity.User;
import com.qc.blogsystemplus.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public int addUser(UserBean user){
        user.setRole_id(1);
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
        user.setRegister_time(sdf.format(new Date()));
        return userMapper.addUser(user);
    }

    public User getUser(String username){
        User user = userMapper.getUser(username);
        return user;
    }

    public List<User> getAllUser(){
        List<User> list = userMapper.getAllUser();
        return list;
    }

    public int updateUser(UserBean userBean) {
        User user = userMapper.getUser(userBean.getUsername());

        if (userBean.getCity() == null){
            userBean.setCity(user.getCity());
        }

        if (userBean.getPassword() == null) {
            userBean.setPassword(user.getPassword());
        }

        if (userBean.getEmail() == null) {
            userBean.setEmail(user.getEmail());
        }

        if (userBean.getNickname() == null) {
            userBean.setNickname(user.getNickname());
        }

        if (userBean.getPhone() == null) {
            userBean.setPhone(user.getPhone());
        }

        int re = userMapper.updateUser(userBean);
        return re;
    }

    public int delUser(String username) {
        return userMapper.delUser(username);
    }
}
